import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created With IntelliJ IDEA
 * Description:leetcode：107. 二叉树的层序遍历 II
 * <a href="https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/">...</a>
 * User: DELL
 * Data: 2023-01-14
 * Time: 23:36
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        if(root == null) {
            return result;
        }
        //辅助队列
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            //记录当前层的所有结点的val
            List<Integer> curLevelVal = new LinkedList<>();
            //这里确定当前层的结点个数
            int count = queue.size();
            for (int i = 0; i < count; i++) {
                TreeNode curNode = queue.poll();
                curLevelVal.add(curNode.val);
                if (curNode.left != null) {
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    queue.offer(curNode.right);
                }
            }
            //每次均头插进入result中
            result.addFirst(curLevelVal);
        }
        return result;
    }
}